/**
 * 
 */
package com.cnhaimei.vod.logic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.TextView;

import com.cnhaimei.com.HListView.MyTouchListner;
import com.cnhaimei.com.PageManager;
import com.cnhaimei.com.PageManager.PageInfoListener;
import com.cnhaimei.com.SearchTextView;
import com.cnhaimei.com.widget.ViewFlow;
import com.cnhaimei.com.widget.ViewFlow.ViewSwitchListener;
import com.cnhaimei.vod.FavoriteManager;
import com.cnhaimei.vod.FavoriteManager.OperateResultType;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.SelSongsManager;
import com.cnhaimei.vod.bean.Song;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.net.dc.Player;
import com.cnhaimei.vod.net.dq.DQClose;
import com.cnhaimei.vod.net.dq.DQQuery;
import com.cnhaimei.vod.net.dq.DQQueryResult;
import com.cnhaimei.vod.net.dq.DQRead;
import com.cnhaimei.vod.net.dq.DQReadResult;
import com.cnhaimei.vod.net.dq.DQSongs;
import com.cnhaimei.vod.net.dq.SongParser;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.Const.QueryType;
import com.cnhaimei.vod.util.Util;

/**
 * 歌曲点歌页面
 * 
 * @author hw <br>
 * @date 2013-5-24
 * 
 */
public class SongListActivity extends VODActivity implements PageInfoListener
, OnItemSelectedListener,MyTouchListner, TextWatcher , ViewSwitchListener{
	private static final int STATE_CLOSE = 0, STATE_OPENING = 1, STATE_OPENED = 2;
	private static final int PAGE_SIZE = 7;
	private static final int BASE_NUM = 10000000;
	private static DQQueryResult queryResult;
	private static long curSearchId = -1;
	private static DQQuery mQuery;
	private int mState = STATE_CLOSE;
	private String mQueryString = DQQuery.QRY_SONG_ALL;//DQQuery.QRY_SONG_LIST;
	private String mTitle = "";
	private static String mLastQueryString;
	private String mQueryStringExtra = DQQuery.QRY_SONG_ALL;
	private String mQueryTable = DQQuery.TABLE_SONG;
	private int mType = QueryType.COMMON;
	
	private boolean mDQConnected = true;
	
//	private GridView bigLstView;
	//private HListView smlLstView;
	private ViewFlow smlLstView;
	private TextView curPageView;
	private TextView totalPageView;
	private AdapterEx mGridAdapter;
	private AdapterEx mListAdapter;
	private View curSelView;

	private View mHeadView;
	private SearchTextView mSearchView;
	private View mCancelView;
	private boolean mSearchViewFocused = false;

	private SparseArray<ArrayList<Song>> mPageCache = new SparseArray<ArrayList<Song>>();
	private LayoutInflater mInflater;
	private PageManager pageManager;
	private ArrayList<Song> curSongList;
	private SongParser songParser;

	private boolean isBigMap = true;

	private HashMap<Long, Integer> pageReq = new HashMap<Long, Integer>(500);
	private HashSet<Integer> loadingIntegerSet = new HashSet<Integer>(50);
	private boolean isClickedSinger;
	
	private View mSelSongView;//更多菜单选中的项，用于onActivityResult时selectItem用

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.v8_song_list);


		String queryTable = getIntent().getStringExtra(Const.Key.QUERY_TABLE);
		if (queryTable != null && queryTable.length() > 0) {
			mQueryTable = queryTable;
		}
		
		String queryStr = getIntent().getStringExtra(Const.Key.QUERY_STRING);
		if (queryStr != null) {
			mQueryStringExtra = queryStr;
			mQueryString = mQueryStringExtra;
		}
		String title = getIntent().getStringExtra(Const.Key.TITLE_NAME);
		if (title != null) {
			mTitle = title;
		}
		else {
			mTitle = this.getResources().getString(R.string.song_title);
		}
		
		mType = getIntent().getIntExtra(Const.Key.QUERY_TYPE, QueryType.COMMON);
		
		if (mLastQueryString != mQueryString) {
			mLastQueryString = mQueryString;
			
			DQManagerDisconnect();
		}	
		
		if (Util.DEMO) {
			curSongList = new ArrayList<Song>(PAGE_SIZE);
			for (int i = 0; i < PAGE_SIZE; i++) {
				curSongList.add(Song.createSong("寒江雪" + (i * 100), "郑源"
						+ (i * 100), "高清"));
			}
		}
		
		mDQConnected = NetManager.G().isDQManagerAlive();
		if (queryResult == null || curSearchId == -1) {
			mState = STATE_CLOSE;
		} else {
			mState = STATE_OPENED;
		}

		initView();

		if (mCancelView != null) {
			mCancelView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mSearchView != null) {
						mSearchView.clearFocus();
						mCancelView.setVisibility(View.GONE);
						mHeadView.setVisibility(View.VISIBLE);
						mSearchView.setText("");
					}					

					search(null);
				}
			});
		}
		if (mSearchView != null) {

			mSearchView.addTextChangedListener(this);//监听输入变化
			
			mSearchView.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					mSearchViewFocused = hasFocus;
				}
			});
			mSearchView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					if (mSearchViewFocused) {
//						mCancelView.setVisibility(View.VISIBLE);
//						mHeadView.setVisibility(View.GONE);
//					}
				}
			});
			mSearchView.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
					if(event.getAction() == KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){//修改回车键功能
						String search = mSearchView.getText().toString();
						search = search.trim();
						//if (search.length() > 0) 
						{
							
							// 先隐藏键盘
							((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
											SongListActivity.this
											.getCurrentFocus()
											.getWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

							search(search);
						}
					}
				
					return false;					
				}
			});
		}
		
		pageManager = new PageManager();
		pageManager.setPageButtonView(findViewById(R.id.pre_page),
				findViewById(R.id.next_page), null, null);
		if (Util.DEMO) {
			pageManager.setPageInfo(1, 4, false);
		}
		pageManager.setListener(this);

		setShowMode(false);

		XVod.G().registerListener(EventsManager.Event.QUERY_RESPONSE, this);
		XVod.G().registerListener(EventsManager.Event.QUERY_RECORDS, this);
		XVod.G().registerListener(EventsManager.Event.QUERY_QUERY,this);
		XVod.G().registerListener(EventsManager.Event.SELECT_SONG_RESULT, this);
		
		
		smlLstView.setOnItemSelectedListener(this);
		//smlLstView.setmMyTouchListner(this);
		
		query(true);
	}
	
	public void search(String search) {
		//清除原先的显示
		 if (queryResult != null) {
			 final DQQueryResult q = queryResult;
			 queryResult = null;
			 XVod.G().addRequest(new DQClose(q.getSnap()));
			 pageReq.clear();
			 mPageCache.clear();
			 loadingIntegerSet.clear();
		 }
		
		//搜索
		if (search != null && search.length() > 0) {
			int len = -1;
			try {
				len = Integer.parseInt(search);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if (len > 0 && len < 9) {
				mQueryString = DQQuery.getSongsByLength(len, mQueryStringExtra);
			} else {
				mQueryString = DQQuery.createSongLikeName(search, mQueryStringExtra);
			}
		}
		else {
			mQueryString = mQueryStringExtra;
		}
		if (mLastQueryString != mQueryString) {
			mLastQueryString = mQueryString;
			
			pageManager.setCurrentIndex(0, false);
			
			DQManagerDisconnect();		
			
			mDQConnected = NetManager.G().isDQManagerAlive();
			if (queryResult == null || curSearchId == -1) {
				mState = STATE_CLOSE;
			} else {
				mState = STATE_OPENED;
			}
			query(false);
		}				
	}
	
	public void query(boolean isInit) {
		if (!mDQConnected) {
			return ;
		}
		if (mState == STATE_CLOSE) {
			mQuery = new DQQuery(mQueryTable, mQueryString);
			mState = STATE_OPENING;
			curSearchId = XVod.G().addRequest(mQuery);
		} else if (mState == STATE_OPENED && queryResult != null) {
			songParser = new SongParser(queryResult);
			
			int total = queryResult.getRecordTotal();
			int pageCount = (total > 0 ? total - 1 : 0) / PAGE_SIZE + 1;
			pageManager.setPageInfo(pageManager.getCurrentIndex(), pageCount,
					false);
			// <== 20111010 modify
			if (isInit){
				resetLstView();
			} else {
				loadData(songParser, pageManager.getCurrentIndex());
			}
			// <== 20111010 end
			
			if (curPageView != null) {
//				curPageView.setText(String.valueOf(pageManager.getCurrentIndex() + 1));
				curPageView.setText(getString(R.string.cur_page, pageManager
						.getCurrentIndex() + 1));
			}
			if (totalPageView != null) {
//				totalPageView.setText(String.valueOf(Math.max(pageCount, 1)));
				totalPageView.setText(getString(R.string.total_page, total));
			}
		}
	}
	
	// 重设
	private void resetLstView() {
		/*
		int count = pageManager.getTotalPage();
		int startPos = 0;
		if (count > 0) {
			startPos = BASE_NUM / count * count;
		}
		smlLstView.setSelection(startPos);
		if (mListAdapter != null) {
			mListAdapter.notifyDataSetChanged();
		}
		*/
		smlLstView.setSelection(0);
		if (mListAdapter != null) {
			mListAdapter.notifyDataSetChanged();
		}		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		isClickedSinger = false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (isFinishing()) {
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_RESPONSE, this);
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_RECORDS, this);
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_QUERY,this);
			XVod.G().unRegisterListener(EventsManager.Event.SELECT_SONG_RESULT, this);
			pageReq.clear();
		}
	}

	@Override
	protected void onDestroy() {
		 if (queryResult != null) {
			 final DQQueryResult q = queryResult;
			 queryResult = null;
			 XVod.G().addRequest(new DQClose(q.getSnap()));
		 }
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.big_map:
			if (isBigMap) {
				break;
			}
			curSelView = null;
			setShowMode(true);
			break;
		case R.id.list_bt:
			if (!isBigMap) {
				break;
			}
			curSelView = null;
			setShowMode(false);
			break;
		case R.id.pre_page:
			break;
		case R.id.next_page:
			break;
		case R.id.goback:
			close();
			break;
		default:
			super.onClick(v); // need parent
			break;
		}
	}
	
	public static void DQManagerDisconnect(){
		curSearchId = -1;
		queryResult = null;
	}
	
	protected void onDQManagerDisconnect() {
		mDQConnected = false;
		songParser = null;
		mState = STATE_CLOSE;
		loadingIntegerSet.clear();
	}
	
	protected void onDQManagerReconnect() {
		mDQConnected = true;
		curSearchId = -1;
		queryResult = null;
		mState = STATE_CLOSE;
		loadingIntegerSet.clear();
//		query();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Song tmpSong = null;
		if (data != null){
			Serializable tmpSerializable = data.getSerializableExtra(Const.Key.SONG_INFO);
			if (tmpSerializable != null && tmpSerializable instanceof Song) {
				tmpSong = (Song)tmpSerializable;
			}
			else {
				return;
			}
		}
		if (requestCode == Const.RequestCode.SEL_SONG_MORE)
		{
			switch(resultCode)
			{
			case Const.ResultCode.SEL_SONG:
				XVod.G().insertSong(tmpSong);
				if (mSelSongView != null) {
					selectItem(mSelSongView);
				}
				//showMyToast("点播歌曲成功");
				break;
			case Const.ResultCode.INSERT_SONG:
				final Player p = Player.G();
				if (p.getPlaylistCount() < Player.MAX_SEL) {
					int count = p.getPlaylistCount();
					XVod.G().insertSong(tmpSong);
					XVod.G().preSortSong(count, 1); 
				}
				if (mSelSongView != null) {
					selectItem(mSelSongView);
				}
				showMyToast("插播歌曲置顶成功");
				break;
			case Const.ResultCode.SEL_SINGER:
				//StarSongsActivity.starActivity(SongListActivity.this, tmpSong.getSinger());
				Intent intent = new Intent(Const.Action.ShowStarsSongs);	
				intent.putExtra(StarSongsActivity.EXTRA_KEY_NAME, tmpSong.getSinger());
				intent.putExtra(Const.Key.QUERY_TABLE, mQueryTable);
				intent.putExtra(Const.Key.QUERY_TYPE, QueryType.FILM);
				SongListActivity.this.startActivity(intent);
				break;
			case Const.ResultCode.ADD_FAVORITE:
				OperateResultType type = FavoriteManager.G().addSong(tmpSong);
				if (type == OperateResultType.SUCCESS) {
					showMyToast("添加收藏成功！");
				} 
				else if (type == OperateResultType.EXIST_ALREADY) {
					showMyToast("已经收藏过该歌曲！");
				}
				break;
			}
		}
	}
	
	@Override
	public void onEvent(int event, Object obj, boolean isSuc) {
		switch (event) {
		case EventsManager.Event.SELECT_SONG_RESULT:
			String str = (String)obj;
			if (str.equals("0")) {
				showMyToast("点播歌曲成功");
			}
			else if (str.equals("-1")) {
				showMyToast("歌曲已在‘已选’列表中");
			} 
			else {
				showMyToast("点播歌曲失败，请重试");
			}
			break;
		case EventsManager.Event.QUERY_RESPONSE: {
			Log.e("onEvent", "isSuc " + isSuc);
			DQQueryResult res = (DQQueryResult) obj;
			if (isSuc) {
				if (res != null && curSearchId == res.getId()) {
					Log.e("SongListActivity", "in curSearchId:" + curSearchId
							+ "res:" + res.getId());
					queryResult = (DQQueryResult) obj;
					if (queryResult.getRecordTotal() > 0) { // 服务器在重启后返回的是0记录，在此定义为无效查询
						songParser = new SongParser(queryResult);
						mState = STATE_OPENED;
						// 20111010 <==
//						loadData(songParser, pageManager.getCurrentIndex());
						// 20111010 <==
						
						
						int total = queryResult.getRecordTotal();
						int pageCount = (total > 0 ? total - 1 : 0) / PAGE_SIZE
								+ 1;
						pageManager.setPageInfo(pageManager.getCurrentIndex(),
								pageCount, false);

						if (curPageView != null) {
//							curPageView.setText(String.valueOf(pageManager
//									.getCurrentIndex() + 1));
//							totalPageView.setText(String.valueOf(Math.max(
//									pageCount, 1)));
							curPageView.setText(getString(R.string.cur_page, pageManager
									.getCurrentIndex() + 1));
							totalPageView.setText(getString(R.string.total_page, Math.max(pageCount, 1)));
						}
						// 20111010 ==>
						resetLstView();
						// 20111010 ==> end
						
					} else {
						XVod.G().addRequest(new DQClose(queryResult.getSnap()));
						mState = STATE_CLOSE;
						curSearchId = -1;
						queryResult = null;
						pageReq.clear();
						mPageCache.clear();
						loadingIntegerSet.clear();
						pageManager.setPageInfo(1, 1, true);
						//resetLstView();
						refreshPage();
					}
				}
			} else if (curSearchId == res.getId()) {

				if (mQuery != null && !mQuery.isSetToClose()) {
					XVod.G().addRequest(new DQClose(mQuery.getSnap()));
				}
				mState = STATE_CLOSE;
				curSearchId = -1;
			}
		}
			break;
		case EventsManager.Event.QUERY_RECORDS: {
			if (obj instanceof DQReadResult) {
				DQReadResult records = (DQReadResult) obj;
				if (isSuc && mState == STATE_OPENED) {// queryResult != null) {
					long id = records.getId();
					Integer pg = pageReq.get(id);
					if (pg != null) {
						DQSongs songs = (DQSongs) obj;
						mPageCache.put(songs.getBegin(), songs.getList());
						loadingIntegerSet.remove(songs.getBegin());
						// if (pageManager.getCurrentIndex() == pg) {
						// curSongList = songs.getList();
						refreshPage();
						// }
					} else {
						loadingIntegerSet.clear();
					}
				}
				if (records.getSnap() == 0) {
					mState = STATE_CLOSE;
				}
			}
		}
			break;
		case EventsManager.Event.QUERY_QUERY: {
			if (!isSuc) {
				mState = STATE_CLOSE;
			}
		} break;

		default:
			break;
		}
		super.onEvent(event, obj, isSuc);
	}

	public void onPageIndexChanged(int prePageIndex, int currentPageIndex,
			int totalPages) {
		int count = pageManager.getTotalPage();
		int startPos = 0;
//		if (count > 0) {
//			startPos = BASE_NUM / count * count;
//		}
		
		startPos += currentPageIndex;
		
		smlLstView.setSelection(startPos);
		int total = Math.max(1, pageManager.getTotalPage());

		if (curPageView != null) {
//			curPageView.setText(String.valueOf(currentPageIndex % total + 1));
//			totalPageView.setText(String.valueOf(total));
			curPageView.setText(getString(R.string.cur_page, currentPageIndex % total + 1));
			totalPageView.setText(getString(R.string.total_page, total));
		}
	}

	public void onPageIndexChangedError(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// TODO Auto-generated method stub

	}

	private void initView() {
		//显示后退按钮
		showBackBtn(true);
		setTitle(mTitle);
		
		mSearchView = (SearchTextView) findViewById(R.id.search_edit);
		mCancelView = findViewById(R.id.cancel_btn);
		mHeadView = findViewById(R.id.head);
		
		curPageView = (TextView) findViewById(R.id.cur_page);
		totalPageView = (TextView) findViewById(R.id.total_page);

		setClickable(R.id.big_map, R.id.list_bt, R.id.pre_page, R.id.next_page,
				R.id.goback);
				
		mInflater = LayoutInflater.from(this);
//		bigLstView = (GridView) findViewById(R.id.big_list);
		smlLstView = (ViewFlow) findViewById(R.id.viewflow);
		smlLstView.setOnViewSwitchListener(this);
		// smlLstView.setCacheColorHint(Color.TRANSPARENT);
//		bigLstView.setNumColumns(4);
//		bigLstView.setCacheColorHint(Color.TRANSPARENT);
	}

	private void setShowMode(boolean isBigMap) {

		this.isBigMap = isBigMap;
		if (isBigMap) {
//			bigLstView.setVisibility(View.VISIBLE);
			smlLstView.setVisibility(View.INVISIBLE);
		} else {
//			bigLstView.setVisibility(View.INVISIBLE);
			smlLstView.setVisibility(View.VISIBLE);
		}
		refreshPage();
	}

	private void refreshPage() {
		if (mListAdapter == null) {
			mListAdapter = new AdapterEx(false);
			smlLstView.setAdapter(mListAdapter);
		}
		mListAdapter.notifyDataSetChanged();
	}

	public void loadData(SongParser sp, int pageIndex) {
		DQRead read = new DQRead(sp);
		read.setRequest(pageIndex * PAGE_SIZE, PAGE_SIZE);
		long id = XVod.G().addRequest(read);
		// long id = XVod.G().requestRecord(sp, pageIndex * PAGE_SIZE,
		// PAGE_SIZE);
		pageReq.put(id, pageIndex);
	}
	
	public ArrayList<Song> readData(int index) {
		
//		if (mState == STATE_CLOSE) {
//			query(false);
//		}
		
		final ArrayList<Song> lst = mPageCache.get(index * PAGE_SIZE);
		
		if (loadingIntegerSet.contains(index * PAGE_SIZE)) {
			return lst;
		}
		
		if (lst == null && mState == STATE_OPENED && songParser != null ) {
			loadingIntegerSet.add(index * PAGE_SIZE);
			loadData(songParser, index);
		}

		return lst;
	}

	private void close() {
		finish();
	}

	public class AdapterEx extends BaseAdapter implements OnTouchListener, OnClickListener {
		private boolean isBigmap;		

		public AdapterEx(boolean isBigmap) {
			this.isBigmap = isBigmap;
		}

		public int getCount() {
			int total = Math.max(0,pageManager.getTotalPage());
			if (total <= 1) {
				return total;
			}
			return total;//Integer.MAX_VALUE;// lst == null ? 0 : lst.size();
		}

		public Object getItem(int position) {
			return null;// lst.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.v8_page_items, null);
				convertView.setLayoutParams(new Gallery.LayoutParams(
						Gallery.LayoutParams.FILL_PARENT,
						Gallery.LayoutParams.FILL_PARENT));
				holder = new ViewHolder();
				holder.initView(convertView, this, this);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			int total = Math.max(1,pageManager.getTotalPage());
			int page = position % total;
			ArrayList<Song> lst = readData(page);//mPageCache.get(PAGE_SIZE*position);
			holder.setValues(lst, page);
			
			return convertView;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (isNeting) {
				return;
			}
		}

		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag instanceof Song) {
				switch (v.getId()) {
				case R.id.name:
				case R.id.add:
					selectItem((View)v.getParent());
					XVod.G().insertSong((Song) tag);
					//showMyToast("点播歌曲成功");
					break;
//				case R.id.insert: {
//					final Player p = Player.G();
//					if (p.getPlaylistCount() < Player.MAX_SEL) {
//						int count = p.getPlaylistCount();
//						XVod.G().insertSong((Song) tag);
//						XVod.G().preSortSong(count, 1); // 1??
//					}
//				}
//					break;

				case R.id.access: {
					/*
					final Player p = Player.G();
					if (p.getPlaylistCount() < Player.MAX_SEL) {
						int count = p.getPlaylistCount();
						XVod.G().insertSong((Song) tag);
						XVod.G().preSortSong(count, 1); // 1??
					}
					*/

					Intent i = new Intent(Const.Action.SelSongMore);
					i.putExtra(Const.Key.SONG_INFO, (Song) tag);
					startActivityForResult(i, Const.RequestCode.SEL_SONG_MORE);
					mSelSongView = (View)v.getParent();
				}
				break;
				case R.id.singer: {

				}
				break;
				default:
					break;
				}
			}

		}
		
		public boolean onTouch(View v, MotionEvent event) {
			//selectItem(v);
			return false;
		}

	}

	private void selectItem(View itemRoot) {
		if (curSelView == itemRoot) {
			return ;
		}
		/*
		if (curSelView != null) {
			SubViewHolder vhOld = (SubViewHolder) curSelView.getTag();
			curSelView.setBackgroundDrawable(null);
			//vhOld.preImag.setBackgroundResource(R.drawable.img_normal);
			//vhOld.operate.setVisibility(View.INVISIBLE);
			//vhOld.singer.setSelected(false);
		}
		*/
		curSelView = itemRoot;
		if (curSelView != null) {
			SubViewHolder vh = (SubViewHolder) itemRoot.getTag();
			//curSelView.setBackgroundResource(R.drawable.choosing);
			
			TextView nameView = (TextView)curSelView.findViewById(R.id.name);
			if (nameView != null) {
				nameView.setTextColor(getResources().getColor(R.color.blue_color));
			}
			//vh.preImag.setSelected(true);
			//vh.operate.setVisibility(View.VISIBLE);
			//vh.singer.setSelected(true);
			//vh.preImag.setBackgroundResource(R.drawable.img_pressed);
		}
	}

	private void unselectItem(View itemRoot) {
		if (itemRoot != null) {
			TextView nameView = (TextView)itemRoot.findViewById(R.id.name);
			if (nameView != null) {
				nameView.setTextColor(getResources().getColor(R.color.white_color));
			}
		}
	}

	public int getDefinionResId(Song s) {
		String def = s.getDefinition();
		if (Const.SongType.MTV.equals(def)) {
			return R.drawable.song_mtv;
		} else if (Const.SongType.CONCERT.equals(def)) {
			return R.drawable.song_concert;
		} else if (Const.SongType.HIGH.equals(def)) {
			return R.drawable.song_high;
		} else {
			return -1;
		}
	}

	class ViewHolder {

		public View root;
		// public ListView listView;
		// public SubAdapterEx subAdapterEx;
		public View[] rows = new View[PAGE_SIZE];

		public ViewHolder() {
		}

		public void initView(View layout, OnClickListener lis, OnTouchListener touch) {
			root = layout;
			rows[0] = root.findViewById(R.id.row1);
			rows[1] = root.findViewById(R.id.row2);
			rows[2] = root.findViewById(R.id.row3);
			rows[3] = root.findViewById(R.id.row4);
			rows[4] = root.findViewById(R.id.row5);
			rows[5] = root.findViewById(R.id.row6);
			rows[6] = root.findViewById(R.id.row7);

			for (int i = 0; i < rows.length; i++) {
				SubViewHolder subHolder = initSubView(rows[i], lis);
				rows[i].setTag(subHolder);
				rows[i].setOnTouchListener(touch);
			}
		}

		private SubViewHolder initSubView(View layout, OnClickListener lis) {
			SubViewHolder subHolder = new SubViewHolder();
			//subHolder.preImag = (TextView) layout.findViewById(R.id.img);
			subHolder.name = (TextView) layout.findViewById(R.id.name);
			subHolder.singer = (TextView) layout.findViewById(R.id.singer);
			//subHolder.definion = (TextView) layout.findViewById(R.id.definition);
			//subHolder.operate = layout.findViewById(R.id.operate);
			subHolder.add = layout.findViewById(R.id.add);
			//subHolder.insert = layout.findViewById(R.id.insert);
			subHolder.access = layout.findViewById(R.id.access);
			subHolder.add.setOnClickListener(lis);
			//subHolder.insert.setOnClickListener(lis);
			subHolder.access.setOnClickListener(lis);
			
			subHolder.name.setOnClickListener(lis);
			return subHolder;
		}

		public void setValues(ArrayList<Song> lst, int pos) {
			int songSize = lst == null ? 0 : lst.size();
			for (int i = 0; i < rows.length; i++) {
				if (i < songSize) {
					rows[i].setVisibility(View.VISIBLE);
					setSubValues(lst.get(i), (SubViewHolder) rows[i].getTag(),
							pos * PAGE_SIZE + i);
					if (SelSongsManager.G().isSongSelected(lst.get(i))) {
						selectItem(rows[i]);
					}
					else {
						unselectItem(rows[i]);
					}
				} else {
					rows[i].setVisibility(View.INVISIBLE);
					setSubValues(null, (SubViewHolder) rows[i].getTag(), pos * PAGE_SIZE + i);
				}
			}
		}

		private void setSubValues(Song s, SubViewHolder holder, int pos) {
			holder.setValues(s, pos);
		}
	}

	class SubViewHolder {
		public TextView name;
		public TextView singer;
		//public TextView definion;
		//public TextView preImag;
		//public View operate;
		public View add;
		//public View insert;
		public View access;

		public void setValues(Song data, int pos) {
			if (data == null) {
				name.setTag(data);
				add.setTag(data);
//				insert.setTag(data);
				access.setTag(data);
				name.setText(null);
				//definion.setBackgroundDrawable(null);
				//operate.setVisibility(View.INVISIBLE);
				return;
			}
			name.setText(data.getName());
			singer.setText(data.getSingerName());
//			int def = getDefinionResId(data);
//			if (def == -1) {
//				definion.setBackgroundDrawable(null);
//			} else {
//				definion.setBackgroundResource(def);
//			}
			add.setTag(data);
//			insert.setTag(data);
			access.setTag(data);
			name.setTag(data);
		}
	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		int total = Math.max(1,pageManager.getTotalPage());
		
		pageManager.setCurrentIndex(position % total, false);
	}

	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
	}
	
	private float oldX;
	private final float diff = 5;
	private Rect rect = new Rect();
//	private long clickTime = 0;
	
	@Override
	public void onSwitched(View view, int position) {
		// TODO Auto-generated method stub

		mHandle.removeMessages(1);
		mHandle.sendEmptyMessageDelayed(1, 5);
	}
	
	public void onMyTouchListner(float x, float y, int e) {
		/*
		if (e == HListView.MyTouchListner.EVENT_DOWN) {
			oldX = x;
			return;
		} 
		else if (e == HListView.MyTouchListner.EVENT_UP 
				|| e == HListView.MyTouchListner.EVENT_CANCEL) {
			if (Math.abs(oldX - x) < diff) {
				View root = smlLstView.getSelectedView();
				if (root == null || root.getTag() == null
						|| root.getVisibility() != View.VISIBLE) {
					return;
				}
				ViewHolder vh = (ViewHolder) root.getTag();
				int index = (((int) (y - 63)) / vh.rows[0].getHeight())
						% PAGE_SIZE;
				Object suTag = vh.rows[index].getTag();
				if (suTag instanceof SubViewHolder) {
					SubViewHolder subHodler = (SubViewHolder) suTag;
					//subHodler.singer.getGlobalVisibleRect(rect);
					if (rect.contains((int)x, (int)y) && !isClickedSinger) {
						Log.e("ssi", "click");
						isClickedSinger = true;
						//StarSongsActivity.starActivity(SongListActivity.this, ((TextView) subHodler.singer).getText().toString());
						return;
					}
				}
			}
			if (e == HListView.MyTouchListner.EVENT_UP) {
				mHandle.removeMessages(1);
				mHandle.sendEmptyMessageDelayed(1, 200);
			}
		}
		*/
	}
		
	private Handler mHandle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int total = Math.max(1,pageManager.getTotalPage());
			int position = smlLstView.getSelectedItemPosition();
			
			pageManager.setCurrentIndex(position % total, false);
			if (position >= 0) {
				if (curPageView != null) {
					//curPageView.setText(String.valueOf(position % total + 1));
					//totalPageView.setText(String.valueOf(total));
					curPageView.setText(getString(R.string.cur_page, position % total + 1));
					totalPageView.setText(getString(R.string.total_page, total));
				}
			}
		}
		
	};
	

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

	long currentTime = System.currentTimeMillis(); 
    @Override
    public void afterTextChanged(Editable s) {
		mSearchHandler.removeMessages(0);

		String search = s.toString();
		if (search.trim().equals("")) {
			mSearchWord = null;
		}
		else {
			mSearchWord = search;
		}
		
  	  	mSearchHandler.sendEmptyMessageDelayed(0, 500);
		currentTime = System.currentTimeMillis(); 
    }

	String mSearchWord = "";
	String mLastSearchWord = "";
	
	//定义Handler对象
	private Handler mSearchHandler = new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      try {
	    	  mSearchHandler.removeMessages(0);
	    	  if (mSearchWord != mLastSearchWord) {
		    	  search(mSearchWord);
		    	  mLastSearchWord = mSearchWord;
	    	  }
	      }
	      catch(Exception e)
	      {
	    	  
	      }
	   }
	};
}
